<template>
  <el-dialog v-model="visible" height="80%" width="80%">
    <el-row :gutter="20" class="chart-layout">
      <!-- 左侧：预览和数据源 -->
      <el-col :span="12">
        <div class="left-panel">
          <!-- 图表预览 -->
          <el-card class="preview-card">
            <template #header>
              <div class="card-header">
                <span>图表预览</span>
                <el-button type="primary" size="small" @click="exportChart" :disabled="!hasValidData">
                  导出图片
                </el-button>
              </div>
            </template>

            <div class="preview-content">
              <!-- 动态图表组件 -->
              <component :is="currentChartComponent" :data="chartData" :config="chartConfig" height="400px"
                @refresh="refreshChart" ref="chartRef" />
            </div>
          </el-card>

          <!-- 数据源配置 -->
          <el-card class="data-source-card">
            <template #header>
              <span>数据源配置</span>
            </template>

            <el-form :model="dataFilters" label-width="100px">
              <el-form-item label="数据类型">
                <el-select v-model="dataFilters.dataType" placeholder="选择数据类型">
                  <el-option label="默认数据" value="default" />
                  <el-option label="销售数据" value="sales" />
                  <el-option label="用户数据" value="users" />
                </el-select>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="fetchData" :loading="loading">
                  <el-icon>
                    <Search />
                  </el-icon>
                  搜索数据
                </el-button>
                <el-button @click="resetFilters">
                  重置
                </el-button>
              </el-form-item>
            </el-form>

            <!-- 数据预览 -->
            <div v-if="hasData" class="data-preview">
              <h4>数据预览:</h4>
              <el-tag type="info" style="margin-bottom: 8px;">
                数组字段: {{ arrayFields.join(', ') }}
              </el-tag>
              <pre>{{ JSON.stringify(chartData, null, 2) }}</pre>
            </div>
          </el-card>
        </div>
      </el-col>

      <!-- 右侧：图表配置 -->
      <el-col :span="12">
        <el-card class="config-card">
          <template #header>
            <span>图表配置</span>
          </template>

          <!-- 基础配置 -->
          <div class="config-section">
            <h4>基础配置</h4>
            <el-form :model="chartConfig" label-width="80px">
              <el-form-item label="图表类型">
                <el-select v-model="chartConfig.type" @change="onChartTypeChange">
                  <el-option label="单个数字" value="number" />
                  <el-option label="柱状图" value="bar" />
                  <el-option label="折线图" value="line" />
                  <el-option label="饼图" value="pie" />
                  <el-option label="仪表盘" value="gauge" />
                </el-select>
              </el-form-item>

              <el-form-item label="图表标题">
                <el-input v-model="chartConfig.title" placeholder="输入图表标题" />
              </el-form-item>
            </el-form>
          </div>

          <!-- 动态配置区域 -->
          <div class="config-section">
            <h4>图表配置</h4>

            <!-- 柱状图配置 -->
            <div v-if="chartConfig.type === 'bar'" class="chart-specific-config">

              <el-form :model="chartConfig.option" label-width="100px">
                <el-form-item label="X轴字段">
                  <el-select v-model="chartConfig.option.xAxis" placeholder="选择X轴字段" :disabled="!hasData">
                    <el-option v-for="key in arrayFields" :key="key" :label="`${key} [${chartData[key]?.length || 0}]`"
                      :value="key" />
                  </el-select>
                  <div class="field-tip">选择包含类别名称的数组字段</div>
                </el-form-item>

                <el-form-item label="Y轴字段">
                  <el-select v-model="chartConfig.option.yAxis" multiple placeholder="选择Y轴字段" :disabled="!hasData">
                    <el-option v-for="key in numericArrayFields" :key="key"
                      :label="`${key} [${chartData[key]?.length || 0}]`" :value="key" />
                  </el-select>
                  <div class="field-tip">选择包含数值的数组字段（可多选）</div>
                </el-form-item>

                <el-form-item label="图表方向" v-if="hasValidData">
                  <el-radio-group v-model="chartConfig.option.layout">
                    <el-radio label="vertical">纵向</el-radio>
                    <el-radio label="horizontal">横向</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item label="标签倾斜" v-if="hasValidData">
                  <el-slider v-model="chartConfig.option.rotate" :min="0" :max="90" show-input />
                </el-form-item>

                <el-form-item label="显示数值" v-if="hasValidData">
                  <el-switch v-model="chartConfig.option.showLabel" />
                </el-form-item>

                <el-form-item label="文本尺寸" v-if="hasValidData">
                  <el-slider v-model="chartConfig.option.fontSize" :min="10" :max="24" show-input />
                </el-form-item>

                <el-form-item label="小数位数" v-if="hasValidData">
                  <el-slider v-model="chartConfig.option.decimalPlaces" :min="0" :max="4" show-input />
                </el-form-item>
              </el-form>
            </div>

            <!-- 折线图配置 -->
            <div v-else-if="chartConfig.type === 'line'" class="chart-specific-config">
              <el-alert v-if="!hasValidData" title="请选择X轴和Y轴字段以显示图表" type="warning" :closable="false" show-icon
                style="margin-bottom: 16px;" />

              <el-form :model="chartConfig.option" label-width="100px">
                <el-form-item label="X轴字段">
                  <el-select v-model="chartConfig.option.xAxis" placeholder="选择X轴字段" :disabled="!hasData">
                    <el-option v-for="key in arrayFields" :key="key" :label="`${key} [${chartData[key]?.length || 0}]`"
                      :value="key" />
                  </el-select>
                  <div class="field-tip">选择包含类别名称的数组字段</div>
                </el-form-item>

                <el-form-item label="Y轴字段">
                  <el-select v-model="chartConfig.option.yAxis" multiple placeholder="选择Y轴字段" :disabled="!hasData">
                    <el-option v-for="key in numericArrayFields" :key="key"
                      :label="`${key} [${chartData[key]?.length || 0}]`" :value="key" />
                  </el-select>
                  <div class="field-tip">选择包含数值的数组字段（可多选）</div>
                </el-form-item>

                <el-form-item label="显示数值" v-if="hasValidData">
                  <el-switch v-model="chartConfig.option.showLabel" />
                </el-form-item>

                <el-form-item label="文本尺寸" v-if="hasValidData">
                  <el-slider v-model="chartConfig.option.fontSize" :min="10" :max="24" show-input />
                </el-form-item>

                <el-form-item label="小数位数" v-if="hasValidData">
                  <el-slider v-model="chartConfig.option.decimalPlaces" :min="0" :max="4" show-input />
                </el-form-item>

                <el-form-item label="平滑曲线" v-if="hasValidData">
                  <el-switch v-model="chartConfig.option.smooth" />
                </el-form-item>

                <el-form-item label="显示标记点" v-if="hasValidData">
                  <el-switch v-model="chartConfig.option.showSymbol" />
                </el-form-item>
              </el-form>
            </div>

            <!-- 饼图配置 -->
            <div v-else-if="chartConfig.type === 'pie'" class="chart-specific-config">

              <el-form :model="chartConfig.option" label-width="100px">
                <el-form-item label="名称字段">
                  <el-select v-model="chartConfig.option.nameField" placeholder="选择名称字段" :disabled="!hasData">
                    <el-option v-for="key in arrayFields" :key="key" :label="`${key} [${chartData[key]?.length || 0}]`"
                      :value="key" />
                  </el-select>
                  <div class="field-tip">选择包含类别名称的数组字段</div>
                </el-form-item>

                <el-form-item label="数值字段">
                  <el-select v-model="chartConfig.option.valueField" placeholder="选择数值字段" :disabled="!hasData">
                    <el-option v-for="key in numericArrayFields" :key="key"
                      :label="`${key} [${chartData[key]?.length || 0}]`" :value="key" />
                  </el-select>
                  <div class="field-tip">选择包含数值的数组字段</div>
                </el-form-item>

                <el-form-item label="显示标签" v-if="hasValidData">
                  <el-switch v-model="chartConfig.option.showLabel" />
                </el-form-item>

                <el-form-item label="显示百分比" v-if="hasValidData">
                  <el-switch v-model="chartConfig.option.showPercentage" />
                </el-form-item>

                <el-form-item label="文本尺寸" v-if="hasValidData">
                  <el-slider v-model="chartConfig.option.fontSize" :min="10" :max="24" show-input />
                </el-form-item>

                <el-form-item label="小数位数" v-if="hasValidData">
                  <el-slider v-model="chartConfig.option.decimalPlaces" :min="0" :max="4" show-input />
                </el-form-item>
              </el-form>
            </div>

            <!-- 仪表盘配置 -->
            <div v-else-if="chartConfig.type === 'gauge'" class="chart-specific-config">

              <el-form :model="chartConfig.option" label-width="100px">
                <el-form-item label="数值字段">
                  <el-select v-model="chartConfig.option.valueField" placeholder="选择数值字段" :disabled="!hasData">
                    <el-option v-for="key in allFields" :key="key" :label="`${key} (${getFieldType(key)})`"
                      :value="key" />
                  </el-select>
                  <div class="field-tip">选择包含数值的字段</div>
                </el-form-item>

                <el-form-item label="最小值" v-if="chartConfig.option.valueField">
                  <el-input-number v-model="chartConfig.option.min" :min="0" :max="chartConfig.option.max - 1" />
                </el-form-item>

                <el-form-item label="最大值" v-if="chartConfig.option.valueField">
                  <el-input-number v-model="chartConfig.option.max" :min="chartConfig.option.min + 1" />
                </el-form-item>

                <el-form-item label="单位" v-if="chartConfig.option.valueField">
                  <el-input v-model="chartConfig.option.unit" placeholder="如：%、分" />
                </el-form-item>

                <el-form-item label="文本尺寸" v-if="chartConfig.option.valueField">
                  <el-slider v-model="chartConfig.option.fontSize" :min="10" :max="24" show-input />
                </el-form-item>

                <el-form-item label="小数位数" v-if="chartConfig.option.valueField">
                  <el-slider v-model="chartConfig.option.decimalPlaces" :min="0" :max="4" show-input />
                </el-form-item>
              </el-form>
            </div>

            <!-- 单个数字配置 -->
            <div v-else-if="chartConfig.type === 'number'" class="chart-specific-config">

              <el-form :model="chartConfig.option" label-width="100px">
                <el-form-item label="取值字段">
                  <el-select v-model="chartConfig.option.valueField" placeholder="选择数值字段" :disabled="!hasData">
                    <el-option v-for="key in allFields" :key="key" :label="`${key} (${getFieldType(key)})`"
                      :value="key" />
                  </el-select>
                  <div class="field-tip">选择包含数值的字段</div>
                </el-form-item>

                <el-form-item label="单位" v-if="chartConfig.option.valueField">
                  <el-input v-model="chartConfig.option.unit" placeholder="如：元、个" />
                </el-form-item>

                <el-form-item label="字体大小" v-if="chartConfig.option.valueField">
                  <el-slider v-model="chartConfig.option.fontSize" :min="24" :max="72" show-input />
                </el-form-item>

                <el-form-item label="小数位数" v-if="chartConfig.option.valueField">
                  <el-slider v-model="chartConfig.option.decimalPlaces" :min="0" :max="4" show-input />
                </el-form-item>
              </el-form>
            </div>
            <div class="config-section">
              <h4>执行周期</h4>
            </div>
            <div class="config-section">
              <h4>操作</h4>
              <el-button type="primary">保存</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

// API 服务
import { mockDataApi } from '@/api/mockDataApi'

// 配置管理
import { createChartConfig } from './ChartComponent/chartConfig'

// 图表组件
import BarChart from './ChartComponent/BarChart.vue'
import LineChart from './ChartComponent/LineChart.vue'
import NumberChart from './ChartComponent/NumberChart.vue'
import PieChart from './ChartComponent/PieChart.vue'
import GaugeChart from './ChartComponent/GaugeChart.vue'

// 响应式数据
const chartData = ref({})
const loading = ref(false)
const chartRef = ref(null)
const visible = ref(true)

const props = defineProps({ 'modelValue': Boolean })
const emit = defineEmits('update:modelValue')


watch(() => props.modelValue, (val) => {
  visible.value = val
})
watch(visible, (val) => {
  emit('update:modelValue', val)
})

// 数据筛选条件
const dataFilters = ref({
  dataType: 'default'
})

// 图表配置 - 使用新的配置结构
const chartConfig = ref({
  type: 'number',
  title: '',
  option: createChartConfig(),
  cron: {}
})

// 计算属性
const hasData = computed(() => {
  return Object.keys(chartData.value).length > 0
})


// 获取所有字段
const allFields = computed(() => Object.keys(chartData.value))

// 获取数组类型字段
const arrayFields = computed(() => {
  const data = chartData.value
  return Object.keys(data).filter(key =>
    Array.isArray(data[key]) && data[key].length > 0
  )
})

// 获取数值数组字段
const numericArrayFields = computed(() => {
  const data = chartData.value
  return arrayFields.value.filter(key => {
    const arr = data[key]
    return arr.every(item => typeof item === 'number')
  })
})

// 检查是否有有效数据
const hasValidData = computed(() => {
  if (!hasData.value) return false

  if (chartConfig.value.type === 'number') {
    return !!chartConfig.value.option.valueField
  } else {
    // 柱状图和折线图需要X轴和至少一个Y轴
    return !!chartConfig.value.option.xAxis &&
      Array.isArray(chartConfig.value.option.yAxis) &&
      chartConfig.value.option.yAxis.length > 0
  }
})

const currentChartComponent = computed(() => {
  const components = {
    bar: BarChart,
    line: LineChart,
    pie: PieChart,
    gauge: GaugeChart,
    number: NumberChart
  }
  return components[chartConfig.value.type] || BarChart
})

// 方法
// 获取字段类型描述
const getFieldType = (key) => {
  const value = chartData.value[key]
  if (typeof value === 'number') return '数字'
  if (Array.isArray(value)) {
    if (value.every(item => typeof item === 'number')) return '数值数组'
    return `数组[${value.length}]`
  }
  if (typeof value === 'string') return '字符串'
  return typeof value
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const response = await mockDataApi.getChartData(dataFilters.value)

    if (response.success) {
      chartData.value = response.data
      // 自动设置默认的轴字段
      autoSetAxisFields()
      ElMessage.success('数据获取成功')
    }
  } catch (error) {
    ElMessage.error('数据获取失败')
    chartData.value = {}
  } finally {
    loading.value = false
  }
}

// 自动设置轴字段
const autoSetAxisFields = () => {
  if (!hasData.value) return

  const currentType = chartConfig.value.type
  const option = chartConfig.value.option

  if (currentType !== 'number') {
    // 柱状图和折线图
    if (arrayFields.value.length > 0) {
      option.xAxis = arrayFields.value[0]
    }
    if (numericArrayFields.value.length > 0) {
      option.yAxis = [numericArrayFields.value[0]]
    }
  } else {
    // 数字图表 - 极度简化，只设置取值字段
    const numberField = allFields.value.find(key => typeof chartData.value[key] === 'number')
    if (numberField) {
      option.valueField = numberField
    }
  }
}

// 图表类型变化处理
const onChartTypeChange = (newType) => {
  // 重置特定配置
  const oldOptions = chartConfig.value.option
  if (oldOptions) {
    if (chartConfig.value.type !== 'number') {
      oldOptions.xAxis = ''
      oldOptions.yAxis = []
    } else {
      oldOptions.valueField = ''
    }
  }

  if (hasData.value) {
    autoSetAxisFields()
  }
}

// 重置筛选条件
const resetFilters = () => {
  dataFilters.value = {
    dataType: 'default'
  }
}

// 刷新图表数据
const refreshChart = () => {
  fetchData()
}

// 导出图表
const exportChart = () => {
  if (!hasValidData.value) {
    ElMessage.warning('暂无有效数据可导出')
    return
  }
  ElMessage.info('导出功能开发中')
}

// 监听配置变化，实时更新图表
watch(
  () => chartConfig.value,
  () => {
  },
  { deep: true }
)

// 初始化
onMounted(() => {
})
</script>

<style scoped>
.interactive-chart {
  padding: 20px;
  background-color: #f5f7fa;
}

.chart-layout {
  height: 10%;
}

.left-panel {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 20px;
}

.preview-card,
.data-source-card,
.config-card {
  height: auto;
}

.preview-card {
  flex: 1;
}

.data-source-card {
  flex: 0 0 auto;
}

.config-card {
  height: 100%;
  overflow-y: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.preview-content {
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.config-section {
  margin-bottom: 24px;
}

.config-section h4 {
  margin-bottom: 16px;
  color: #303133;
  border-left: 4px solid #409eff;
  padding-left: 8px;
}

.chart-specific-config {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.data-preview {
  margin-top: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.data-preview h4 {
  margin: 0 0 8px 0;
  color: #606266;
  font-size: 14px;
}

.data-preview pre {
  margin: 0;
  font-size: 12px;
  color: #666;
  max-height: 200px;
  overflow-y: auto;
}

.field-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

:deep(.el-slider) {
  margin-top: 8px;
}

:deep(.el-form-item) {
  margin-bottom: 16px;
}
</style>